package com.ciwong.epaper.modules.me.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.MsgPostBean;
import com.ciwong.epaper.bean.MsgtypeBean;
import com.ciwong.epaper.modules.me.bean.RefreshNewBookDesk;
import com.ciwong.epaper.modules.msg.bean.MessageInfo;
import com.ciwong.epaper.modules.msg.bean.MsgTypeConfig;
import com.ciwong.epaper.modules.msg.dao.MsgDao;
import com.ciwong.epaper.modules.msg.util.MessageJumpManager;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.IndicateText;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 书桌首页
 * Created by keepon on 2018/8/6.
 */
public class BookDeskParentFragment extends BaseFragment implements View.OnClickListener {

    private final String TAG = "BookDeskParentFragment";
    private static final int NEW_BOOKDESK = 0;
    private static final int OLD_BOOKDESK = 1;
    private static final String IS_OLD_BOOKDESK_TYPE = "IS_OLD_BOOKDESK_TYPE";

    private FrameLayout mFlCotainer;
    private FragmentManager mChildFragmentManager;
    private FragmentTransaction mFragmentTransaction;
    private TextView mTvGotoMyBooks;
    private TextView mTvSwithFragments;
    private int mCurrentFragmentIndex;
    private EApplication mApplication;
    /**
     * 消息
     */
    private ImageView btn_msg;

    private IndicateText msgCount;
    /**
     * 更新消息数值
     */
    private int msgNum;


    public static BookDeskParentFragment newInstance() {
        BookDeskParentFragment fragment = new BookDeskParentFragment();
        return fragment;
    }

    public BookDeskParentFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_desk_parent, container,
                false);
        findViews(view);
        initEvent();
        init();
        registerBoradcastReceiver();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getLocalMsgCount();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

    private void findViews(View view) {
        mFlCotainer = view.findViewById(R.id.fl_container);
        mTvGotoMyBooks = view.findViewById(R.id.tv_go_to_resource_center);
        mTvSwithFragments = view.findViewById(R.id.tv_switch);

        btn_msg = view.findViewById(R.id.iv_msg);
        msgCount = view.findViewById(R.id.my_work_msg_count);
    }

    private void initEvent() {
        mTvGotoMyBooks.setOnClickListener(this);
        mTvSwithFragments.setOnClickListener(this);
        btn_msg.setOnClickListener(this);
    }

    private void init() {
        boolean isOldTypeBookFragment = false;
        mApplication = (EApplication) mActivity.getApplication();
        mChildFragmentManager = getChildFragmentManager();
        mFragmentTransaction = mChildFragmentManager.beginTransaction();
        if (isOldTypeBookFragment) {
            mFragmentTransaction.add(R.id.fl_container, BookDeskFragment.newInstance());
            mTvSwithFragments.setText("返回新版");
            mTvGotoMyBooks.setText("我的书籍");
            mCurrentFragmentIndex = OLD_BOOKDESK;
        } else {
            mFragmentTransaction.add(R.id.fl_container, NewBookDeskFragment.newInstance());
            mTvSwithFragments.setText("返回旧版");
            mTvGotoMyBooks.setText(getString(R.string.resource_center));
            mCurrentFragmentIndex = NEW_BOOKDESK;
        }
        mFragmentTransaction.commit();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mCurrentFragmentIndex == NEW_BOOKDESK)
            NewBookDeskFragment.newInstance().setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            EventBus.getDefault().post(new RefreshNewBookDesk(false));
        }
    }

    @Override
    public void onClick(View v) {
        if (!DoubleClickCheckUtils.vertify500Duration()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.tv_go_to_resource_center) {
            return;//停止服务
//            if (getString(R.string.resource_center).equals(mTvGotoMyBooks.getText().toString())) {
//                MeJumpManager.jumpToResourseCenterH5Activity(mActivity, R.string.go_back, getResources().getString(R.string.resource_center));
//            } else {
//                EpaperJumpManager.jumpToAddBook(R.string.go_back, mActivity,
//                        BookDeskParentFragment.this, RequestCode.BookDeskResquestCode.REQ_CODE_TO_ADD_BOOK_FROM_BOOK_DESK);
//            }

        } else if (id == R.id.tv_switch) {
            return;
//            if (mCurrentFragmentIndex == NEW_BOOKDESK) {
//                showBookDeskFragmentMode(OLD_BOOKDESK);
//                mCurrentFragmentIndex = OLD_BOOKDESK;
//                mTvSwithFragments.setText("进入新版");
//                mTvGotoMyBooks.setText("我的书籍");
//                UserInfoBase userInfoBase = BaseApplication.getInstance().getUserInfoBase();
//                if (userInfoBase != null) {
//                    CWSys.setSharedBoolean(IS_OLD_BOOKDESK_TYPE + userInfoBase.getUserId(), true);
//                }
//
//            } else {
//                showBookDeskFragmentMode(NEW_BOOKDESK);
//                mCurrentFragmentIndex = NEW_BOOKDESK;
//                mTvSwithFragments.setText("返回旧版");
//                mTvGotoMyBooks.setText(getString(R.string.resource_center));
//                UserInfoBase userInfoBase = BaseApplication.getInstance().getUserInfoBase();
//                if (userInfoBase != null) {
//                    CWSys.setSharedBoolean(IS_OLD_BOOKDESK_TYPE + userInfoBase.getUserId(), false);
//                }
//            }
        } else if (id == R.id.iv_msg) {
            MessageJumpManager.jumpToMsgActivity(mActivity, R.string.go_back, RequestCode.HomeWorkFragmentResquestCode.QEQ_FOR_HOME_WORK_MSG);
        }
    }

    public void showBookDeskFragmentMode(int index) {
        FragmentTransaction ft = mChildFragmentManager.beginTransaction();
        if (index == NEW_BOOKDESK) {
            ft.replace(R.id.fl_container, NewBookDeskFragment.newInstance());
        } else {
            ft.replace(R.id.fl_container, BookDeskFragment.newInstance());
        }
        ft.commit();


    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        //注册广播
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private void unregisterReceiver() {
        if (mBroadcastReceiver != null)
            getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
        }
    };

    /**
     * 获取本地未读消息数量
     */
    public void getLocalMsgCount() {

        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_NO_READ_MSG_COUNT_NEW, new BaseCallBack() {
            @Override
            public void success(Object data) {
                if (data != null) {
                    List<MessageInfo> counts = (List<MessageInfo>) data;
                    setMsgNum(counts);
                }
                //先从本地获取数据，再从网络获取数据
                getNetMsgCount();
            }

            @Override
            public void failed(int errorCode, Object data) {
                getNetMsgCount();
            }

            @Override
            public void failed(Object data) {
                getNetMsgCount();
            }
        });

    }

    /**
     * 获取网络未读消息数量
     */
    public void getNetMsgCount() {
        UserInfoBase userInfoBase = mApplication.getUserInfoBase();
        if (null != userInfoBase) {

            boolean isGetSuccessFulOnce = ESystem.getSharedBoolean(EConstants.SHARE_KEY_MSG_HAS_GET_SUCESSFUL_ONCE + userInfoBase.getUserId(), false);

            //首先要请求一次getNetMsgList接口，本地保存msgId
            if (!isGetSuccessFulOnce) {
                getNetMsgList(getMsgPostBean(userInfoBase.getUserId()));
                return;
            }
            MsgPostBean msgPostBean = getMsgPostBean(userInfoBase.getUserId());
            String postJson = JsonParserUtil.toJson(msgPostBean);
            MsgDao.getInstance().getNetMsgCountNew(postJson, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    ToastUtil.INSTANCE.toastCenterErrorWithErrorCode("获取未读消息失败", errorCode);
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE, data == null ? "" : "失败信息：" + data.toString(), "获取未读消息失败");
                }

                @Override
                public void failed(Object data) {
//                    ToastUtil.INSTANCE.toastCenterError("获取未读消息失败");
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE, data == null ? "" : "失败信息：" + data.toString(), "获取未读消息失败");
                }

                public void success(Object data) {
                    if (data != null) {
                        List<MessageInfo> counts = (List<MessageInfo>) data;
                        setMsgNum(counts);
                        //从网络获取成功后保存在本地
                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_NO_READ_MSG_COUNT_NEW, (Serializable) counts);
                    }
                }
            });
        }
    }


    private void getNetMsgList(MsgPostBean msgPostBean) {
        final UserInfoBase userInfoBase = mApplication.getUserInfoBase();
        if (null != userInfoBase) {
            String postJson = JsonParserUtil.toJson(msgPostBean);
            MsgDao.getInstance().getMessageListNew(postJson, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                }

                @Override
                public void failed(Object data) {

                }

                public void success(Object data) {
                    if (data != null) {
                        ArrayList<MessageInfo> infos = (ArrayList<MessageInfo>) data;
                        if (infos != null && infos.size() > 0) {
                            for (int i = 0; i < infos.size(); i++) {
                                MessageInfo info = infos.get(i);
                                if (MsgTypeConfig.MSG_SERVICE == info.getMsgGroup()) {
                                    ESystem.setSharedInt(EConstants.SHARE_KEY_MSG_TYPE_SERVICE_MSG_GROUP_ID + userInfoBase.getUserId(), info.getMsgId());
                                } else {
                                    ESystem.setSharedInt(EConstants.SHARE_KEY_MSG_TYPE_HOMEWORK_MSG_GROUP_ID + userInfoBase.getUserId(), info.getMsgId());

                                }
                            }
                            ESystem.setSharedBoolean(EConstants.SHARE_KEY_MSG_HAS_GET_SUCESSFUL_ONCE + userInfoBase.getUserId(), true);
                        }
                    }
                }
            });
        }

    }

    private MsgPostBean getMsgPostBean(long userId) {
        MsgPostBean msgPostBean = new MsgPostBean();
        msgPostBean.setBrandId(EApplication.BRAND_ID);


        msgPostBean.setUserId(userId);
        //作业类型
        MsgtypeBean msgtypeListBeanHomework = new MsgtypeBean();
        int homeworkMsgId = ESystem.getSharedInt(EConstants.SHARE_KEY_MSG_TYPE_HOMEWORK_MSG_GROUP_ID + userId, 0);

        msgtypeListBeanHomework.setMsgId(homeworkMsgId);
        msgtypeListBeanHomework.setMsgGroup(MsgTypeConfig.MSG_WORK_NOTIFICATION);

        //服务类型
        MsgtypeBean msgtypeListBeanMail = new MsgtypeBean();
        int mainMsgId = ESystem.getSharedInt(EConstants.SHARE_KEY_MSG_TYPE_SERVICE_MSG_GROUP_ID + userId, 0);
        msgtypeListBeanMail.setMsgId(mainMsgId);
        msgtypeListBeanMail.setMsgGroup(MsgTypeConfig.MSG_SERVICE);

        List<MsgtypeBean> msgtypeListBeans = new ArrayList<>();
        msgtypeListBeans.add(msgtypeListBeanHomework);
        msgtypeListBeans.add(msgtypeListBeanMail);
        msgPostBean.setMsgtypeList(msgtypeListBeans);
        return msgPostBean;
    }

    /**
     * 发送消息数值
     */
    private void setMsgNum(List<MessageInfo> counts) {
        msgNum = 0;
        for (MessageInfo count : counts) {
            msgNum += count.getMsgCount();
        }
        if (msgNum == 0) {
            msgCount.setVisibility(View.GONE);
        } else {
            msgCount.setVisibility(View.VISIBLE);
            msgCount.setText(msgNum + "");
        }
    }
}
